import torch
from torch import nn
from d2l import torch as d2l
from matplotlib import pyplot as plt


# @save
# @save
class AttentionDecoder(d2l.Decoder):
    """带有注意力机制解码器的基本接口"""

    def __init__(self, **kwargs):
        super(AttentionDecoder, self).__init__(**kwargs)

    @property
    def attention_weights(self):
        raise NotImplementedError


class Seq2SeqAttentionDecoder(AttentionDecoder):
    def __init__(self, vocab_size, embed_size, num_hiddens, num_layers,
                 dropout=0, **kwargs):
        super(Seq2SeqAttentionDecoder, self).__init__(**kwargs)
        self.attention = d2l.AdditiveAttention(
            num_hiddens, num_hiddens, num_hiddens, dropout)
        self.embedding = nn.Embedding(vocab_size, embed_size)
        self.rnn = nn.GRU(
            embed_size + num_hiddens, num_hiddens, num_layers,
            dropout=dropout)
        self.dense = nn.Linear(num_hiddens, vocab_size)

    def init_state(self, enc_outputs, enc_valid_lens, *args):
        # outputs的形状为(batch_size，num_steps，num_hiddens).
        # hidden_state的形状为(num_layers，batch_size，num_hiddens)
        outputs, hidden_state = enc_outputs
        # 10,64,32  2,64,32
        # 编码器输出和编码器输出的隐状态作为解码器的输入
        # 4,7,16,      2,4,16,   None
        # torch.Size([64, 10, 32]) torch.Size([2, 64, 32])
        return (outputs.permute(1, 0, 2), hidden_state, enc_valid_lens)

    def forward(self, X, state):
        # enc_outputs的形状为(batch_size,num_steps,num_hiddens).
        # hidden_state的形状为(num_layers,batch_size,
        # num_hiddens)
        enc_outputs, hidden_state, enc_valid_lens = state
        # 输出X的形状为(num_steps,batch_size,embed_size)
        # torch.Size([64, 10, 32]) torch.Size([2, 64, 32])
        # 201 32 32 2 0.1
        """
        enc_outputs = torch.Size([64, 10, 32])
        hidden_state =  torch.Size([2, 64, 32])
        X =  torch.Size([64, 10])
        """

        X = self.embedding(X).permute(1, 0, 2)
        #  X = torch.Size([10, 64, 32])

        outputs, self._attention_weights = [], []
        for x in X:
            #  torch.Size([2, 64, 32])
            # query的形状为(batch_size,1,num_hiddens)
            # 1,64,32
            # 先选取最后一个状态 64、32 然后再中间插入一个维度变为64，1，32
            # 将最后一个隐藏状态作为查询
            query = torch.unsqueeze(hidden_state[-1], dim=1)
            # print(query.shape,"query.shape")
            # context的形状为(batch_size,1,num_hiddens)
            # 将 key value指定为 经过GRU处理后的信息
            # [64, 1, 32]   [64, 10, 32] [64, 10, 32]
            # 得出来的out信息为  [64,1,32]
            context = self.attention(
                query, enc_outputs, enc_outputs, enc_valid_lens)
            # [64, 1, 16]
            # [64, 1, 32]
            # [25, 1, 32]
            # 在特征维度上连结
            # torch.Size([64, 32]) torch.Size([64, 1, 32])
            # print(x.shape,context.shape,"33333333333333333")
            x = torch.cat((context, torch.unsqueeze(x, dim=1)), dim=-1)
            # 将x变形为(1,batch_size,embed_size + num_hiddens)
            # print(x.shape) torch.Size([64, 1, 64])
            # 1，64，64  2，64，32 16
            out, hidden_state = self.rnn(x.permute(1, 0, 2), hidden_state)
            print(out.shape, "3333")
            outputs.append(out)
            self._attention_weights.append(self.attention.attention_weights)
        # print(len(outputs),"22222222222222222")
        # 全连接层变换后，outputs的形状为
        # (num_steps,batch_size,vocab_size)
        outputs = self.dense(torch.cat(outputs, dim=0))
        # print(outputs.shape,"222222222222222224444444444")
        return outputs.permute(1, 0, 2), [enc_outputs, hidden_state,
                                          enc_valid_lens]

    @property
    def attention_weights(self):
        return self._attention_weights


encoder = d2l.Seq2SeqEncoder(vocab_size=10, embed_size=8, num_hiddens=16,
                             num_layers=2)
encoder.eval()
decoder = Seq2SeqAttentionDecoder(vocab_size=10, embed_size=8, num_hiddens=16,
                                  num_layers=2)
decoder.eval()
X = torch.zeros((64, 10), dtype=torch.long)  # (batch_size,num_steps)
# `output` shape: (`num_steps`, `batch_size`, `num_hiddens`)
# L = 10 N = 32 H = 16
# print(encoder(X)[0].shape)
# `state` shape: (`num_layers`, `batch_size`, `num_hiddens`)
# NL =  2 N = 32 , H = 16
# print(encoder(X)[1].shape)
# print(len(encoder(X)))

state = decoder.init_state(encoder(X), None)
output, state = decoder(X, state)

embed_size, num_hiddens, num_layers, dropout = 32, 32, 2, 0.1
batch_size, num_steps = 64, 10
lr, num_epochs, device = 0.005, 250, d2l.try_gpu()

train_iter, src_vocab, tgt_vocab = d2l.load_data_nmt(batch_size, num_steps)
encoder = d2l.Seq2SeqEncoder(
    len(src_vocab), embed_size, num_hiddens, num_layers, dropout)
# 10,64,32
# print(len(tgt_vocab), embed_size, num_hiddens, num_layers, dropout)
# 201 32 32 2 0.1
decoder = Seq2SeqAttentionDecoder(
    len(tgt_vocab), embed_size, num_hiddens, num_layers, dropout)
net = d2l.EncoderDecoder(encoder, decoder)
d2l.train_seq2seq(net, train_iter, lr, num_epochs, tgt_vocab, device)
#
#
# engs = ['go .', "i lost .", 'he\'s calm .', 'i\'m home .']
# fras = ['va !', 'j\'ai perdu .', 'il est calme .', 'je suis chez moi .']
# for eng, fra in zip(engs, fras):
#     translation, dec_attention_weight_seq = d2l.predict_seq2seq(
#         net, eng, src_vocab, tgt_vocab, num_steps, device, True)
#     print(f'{eng} => {translation}, ',
#           f'bleu {d2l.bleu(translation, fra, k=2):.3f}')
#
# attention_weights = torch.cat([step[0][0][0] for step in dec_attention_weight_seq], 0).reshape((
#     1, 1, -1, num_steps))
#
# # 加上一个包含序列结束词元
# d2l.show_heatmaps(
#     attention_weights[:, :, :, :len(engs[-1].split()) + 1].cpu(),
#     xlabel='Key positions', ylabel='Query positions')
# plt.show()
